package com.zmn.oms.zmn.business.impl.work.autoflow.state;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.conf.channel.ConfOrderChannelBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dro.conf.channel.ConfOrderChannelDRO;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.work.modify.OrderCompleteReviewDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.orderpay.AccountPayBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.state.WorkAutoFlowBService;
import com.zmn.oms.zmn.business.interfaces.work.masterwork.ZsMasterWorkBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @author sunlife
 * @date:2020/9/18 4:32 下午
 * description:
 */
@Slf4j
@Service("flowReviewBService")
public class FlowReviewBServiceImpl<T> implements WorkAutoFlowBService<Object> {

    @Autowired
    ZsMasterWorkBService zsMasterWorkBService;
    @Autowired
    AccountPayBService accountPayBService;

    @Resource
    private ConfOrderChannelBService confOrderChannelBService;

    @Override
    public ResultDTO<Object> condition(OrderWork orderWork) {
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_COMPENSATE)) {
            return ResultDTO.fail("赔偿单不可操作");
        }

        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND)) {
            return ResultDTO.fail("退款单不可操作");
        }

        if (!Objects.equals(orderWork.getBizType(), GlobalConsts.BIZ_TYPE_F)) {
            return ResultDTO.fail("非F端工单不进行自动服务审核");
        }
        if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_SERVICE_COMPLETE)) {
            return ResultDTO.fail("工单非服务完成状态");
        }
        if (Objects.equals(orderWork.getServiceCompleteReviewStatus(), OrderConsts.REVIEW_STATUS_SUCCESS)) {
            return ResultDTO.fail("工单服务完成已审核");
        }
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
            return ResultDTO.success(orderWork);
        }

        ConfOrderChannelDRO confOrderChannelDRO = null;
        try {
            confOrderChannelDRO = confOrderChannelBService.getByChannelId(orderWork.getChannelId());
        } catch (OmsBaseException omsBaseException) {
            omsBaseException.printStackTrace();
        }
        log.info("审核查询渠道详情出参：{}",JSONObject.toJSONString(confOrderChannelDRO));
        if (Objects.isNull(confOrderChannelDRO)) {
            return ResultDTO.fail("无法获取渠道信息");
        }

        // 1不需审核 2保内审核 3保外审核 4 保内&保外审核
        // 订单业务类型：1保外业务（C），2保内业务（F），3工程业务（B）
        Integer auditType = Optional.ofNullable(confOrderChannelDRO.getAuditType()).orElse(1);
        Integer bizType = orderWork.getBizType();

        Boolean needReview = false;
        if ((Objects.equals(bizType, GlobalConsts.BIZ_TYPE_F) && (Objects.equals(auditType, 2) || Objects.equals(auditType, 4))) ||
                (Objects.equals(bizType, GlobalConsts.BIZ_TYPE_C) && (Objects.equals(auditType, 3) || Objects.equals(auditType, 4))) ||
                (Objects.equals(auditType, 1))
        ) {
            needReview = true;
        }
        if (!needReview) {
            return ResultDTO.fail("渠道配置，无需审核");
        }

        // 判断金额是否小于渠道配置
        if (!Objects.equals(auditType, 1) && Objects.nonNull(confOrderChannelDRO.getAuditMinPrice())) {
            Integer auditMinPrice = confOrderChannelDRO.getAuditMinPrice();
            needReview = orderWork.getOriginalAmount() < auditMinPrice;
        }

        // 如果资金账户金额不够，则不可：审核成功
        try {
            accountPayBService.checkAccount(orderWork.getOrderId(),orderWork.getOriginalAmount());
        }catch (OmsBaseException omsException){
            log.info("自动服务完成审核失败：{}", JSON.toJSONString(omsException.getMessage()));
            return ResultDTO.fail(omsException.getMessage());
        }

        if (needReview) {
            return ResultDTO.success(orderWork);
        }else {
            return ResultDTO.fail("价格大于等于渠道配置，需要审核");
        }
    }

    @Override
    public void execute(Object t) {
        try {
            OrderWork orderWork = (OrderWork)t;
            OrderCompleteReviewDTO orderCompleteReviewDTO = new OrderCompleteReviewDTO();
            orderCompleteReviewDTO.setOperator("系统");
            orderCompleteReviewDTO.setOperatorId((long) com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            orderCompleteReviewDTO.setOperatorType(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
            orderCompleteReviewDTO.setOrderId(orderWork.getOrderId());
            orderCompleteReviewDTO.setWorkId(orderWork.getWorkId());
            orderCompleteReviewDTO.setAutoReview(GlobalConsts.YES);
            orderCompleteReviewDTO.setServiceCompleteReviewStatus(OrderConsts.REVIEW_STATUS_SUCCESS);
            orderCompleteReviewDTO.setMasterId(orderWork.getMasterId());
            zsMasterWorkBService.autoReviewComplete(orderCompleteReviewDTO);
        } catch (Exception e) {
            log.info("自动服务审核异常：[{}]", e.getMessage());
        }


    }
}
